package action

import (
	"../global"
	"../model"
	"github.com/go-pg/pg"
	"github.com/labstack/echo"
	"strconv"
	"strings"
	"time"
)

type Brokerage struct{}

//显示所有结算列表
func (*Brokerage) Index(ctx echo.Context) (err error) {
	response := make(map[string]interface{})
	response["error"] = ""

	var query model.Brokerage
	if ctx.QueryParam("status") == "true" {
		query.Status = true
	}

	if ctx.QueryParam("nickname") != "" {
		query.UserID = GetUserID("nickname", ctx.QueryParam("nickname"))
	}
	if ctx.QueryParam("fullname") != "" {
		query.UserID = GetUserID("fullname", ctx.QueryParam("fullname"))
	}
	if ctx.QueryParam("mobile") != "" {
		query.UserID = GetUserID("mobile", ctx.QueryParam("mobile"))
	}

	var BrokerageModel model.BrokerageModel
	res, err := BrokerageModel.GetBrokerage(&query, []string{}, &model.ListParams{})
	if err != nil {
		global.Logger.Error("查询结算记录出错：" + err.Error())
		response["eroor"] = ""
		return ctx.JSON(500, response)
	}
	if len(res) == 0 {
		response["data"] = ""
	} else {
		response["data"] = res
	}

	return ctx.JSON(200, response)
}

//显示单个结算数据
func (*Brokerage) Show(ctx echo.Context) (err error) {
	response := make(map[string]interface{})
	response["error"] = ""

	if ctx.Param("brokerage_id") == "" {
		response["error"] = "缺少结算记录ID字段"
		return ctx.JSON(200, response)
	}
	brokerage_id, err := strconv.ParseInt(ctx.Param("brokerage_id"), 10, 64)
	if err != nil {
		global.Logger.Error("brokerage_id数据类型转换出错：" + err.Error())
		response["error"] = "系统错误"
		return ctx.JSON(500, response)
	}
	var BrokerageModel model.BrokerageModel
	res, err := BrokerageModel.GetBrokerage(&model.Brokerage{ID: brokerage_id}, []string{}, &model.ListParams{Limit: 1})
	if err != nil {
		global.Logger.Error("获取结算记录出错：" + err.Error())
		response["error"] = "系统错误"
		return ctx.JSON(500, response)
	}
	if len(res) == 0 {
		response["error"] = "结算记录不存在"
		return ctx.JSON(200, response)
	}
	response["data"] = res[0]
	return ctx.JSON(200, response)
}

//编辑单个结算数据
func (*Brokerage) Edit(ctx echo.Context) (err error) {
	response := make(map[string]interface{})
	response["error"] = ""

	if ctx.Param("brokerage_id") == "" {
		response["error"] = "缺少结算记录ID字段"
		return ctx.JSON(200, response)
	}

	brokerage_id, err := strconv.ParseInt(ctx.Param("brokerage_id"), 10, 64)
	if err != nil {
		global.Logger.Error("brokerage_id数据类型转换出错：" + err.Error())
		response["erroe"] = "系统错误"
		return ctx.JSON(500, response)
	}

	var BrokerageModel model.BrokerageModel
	res, err := BrokerageModel.GetBrokerage(&model.Brokerage{ID: brokerage_id}, []string{}, &model.ListParams{Limit: 1})
	if err != nil {
		global.Logger.Error("查找结算记录出错：" + err.Error())
		response["error"] = "系统错误"
		return ctx.JSON(500, response)
	}
	if len(res) == 0 {
		response["error"] = "结算记录不存在"
		return ctx.JSON(200, response)
	}

	var query model.Brokerage
	query.ID = res[0].ID
	if ctx.FormValue("status") != "" && ctx.FormValue("status") == "true" {
		query.Status = true
	}
	_, err = global.DB.Model(&query).Set("status=?", query.Status).Update()
	if err != nil {
		global.Logger.Error("修改结算记录出错：" + err.Error())
		response["error"] = "系统错误"
		return ctx.JSON(500, response)
	}

	return ctx.JSON(200, response)
}

//删除结算记录
func (*Brokerage) Delete(ctx echo.Context) (err error) {
	response := make(map[string]interface{})
	response["error"] = ""

	if ctx.Param("brokerage_ids") == "" {
		response["error"] = "缺少参数brokerage_ids"
		return ctx.JSON(200, response)
	}

	var deleteIDs []int64
	var stringIDs []string
	ids := ctx.Param("brokerage_ids")
	stringIDs = strings.Split(ids, ",")
	for _, v := range stringIDs {
		id, err := strconv.ParseInt(v, 10, 64)
		if err != nil {
			global.Logger.Error("brokerage_ids数据类型转换出错")
			response["error"] = "系统错误"
			return ctx.JSON(500, response)
		}
		deleteIDs = append(deleteIDs, id)
	}
	var BrokerageModel model.BrokerageModel
	var brokerage_ids []model.Brokerage
	err = global.DB.Model(&brokerage_ids).Column("id", "status").WhereIn("id IN (?)", pg.In(deleteIDs)).Select()
	if err != nil {
		global.Logger.Error("查找结算记录ID出错：" + err.Error())
		response["error"] = "系统错误"
		return ctx.String(500, err.Error())
	}
	if len(brokerage_ids) != len(deleteIDs) {
		response["error"] = "参数中含有不存在的结算记录ID"
		return ctx.JSON(200, response)
	}

	for _, v := range brokerage_ids {
		if v.Status == false {
			response["error"] = "不能直接删除未完成的结算记录"
			return ctx.JSON(500, response)
		}
	}

	//调用模型删除结算记录
	err = BrokerageModel.DelBrokerage(deleteIDs)
	if err != nil {
		global.Logger.Error("删除结算记录失败：" + err.Error())
		response["error"] = "系统错误"
		return ctx.JSON(500, response)
	}

	return ctx.JSON(200, response)
}

//生成记录
func (*Brokerage) Create(ctx echo.Context) (err error) {
	response := make(map[string]interface{})
	response["error"] = ""

	if ctx.FormValue("amount") == "" {
		response["error"] = "缺少参数amount"
		return ctx.JSON(200, response)
	}

	var query model.Brokerage
	amount, err := strconv.ParseFloat(ctx.FormValue("amount"), 64)
	if err != nil {
		global.Logger.Error("anount数据类型转换出错：" + err.Error())
		response["error"] = "系统错误"
		return ctx.JSON(500, response)
	}
	query.Amount = int64(amount * 100) //乘以100单位转为分，再转为int64，赋值

	if ctx.FormValue("user_id") == "" {
		response["error"] = "缺少参数user_id"
		return ctx.JSON(200, response)
	}
	user_id, err := strconv.ParseInt(ctx.FormValue("user_id"), 10, 64)
	if err != nil {
		global.Logger.Error("user_id数据类型转换出错：" + err.Error())
		response["error"] = "系统错误"
		return ctx.JSON(500, response)
	}
	var UserModel model.UserModel
	res, err := UserModel.GetUser(&model.User{ID: user_id}, []string{"id"}, &model.ListParams{Limit: 1})
	if err != nil {
		global.Logger.Error("查找用户出错：" + err.Error())
		response["error"] = "系统错误"
		return ctx.JSON(500, response)
	}
	if len(res) == 0 {
		response["error"] = "用户不存在"
		return ctx.JSON(500, response)
	}
	ID := global.IDNode.Generate()
	query.ID = ID.Int64()
	query.UserID = res[0].ID
	query.Time = time.Now().Unix()
	//这里应该是开启事物，把用户的未结算金额清空，暂时先不处理
	var BrokerModel model.BrokerageModel
	err = BrokerModel.CreateBrokerage(&query)
	if err != nil {
		global.Logger.Error("创建结算记录出错：" + err.Error())
		response["error"] = "系统错误"
		return ctx.JSON(500, response)
	}
	return ctx.JSON(200, response)
}
